package com.qixin.activiti.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qixin.activiti.service.IEaRepaymentbillBXNCItfService;
import com.qixin.activiti.utils.EaListenerUtil;
import com.qixin.modules.ea.service.IEaBookDetailService;
import com.qixin.modules.ea.service.IEaCommunicationsService;
import com.qixin.modules.eaLoan.entity.EaLoanbill;
import com.qixin.modules.eaLoan.entity.EaRepaymentbill;
import com.qixin.modules.eaLoan.service.IEaLoanbillService;
import com.qixin.modules.eaLoan.service.IEaRepaymentbillService;
import com.qixin.modules.log.entity.SysInterfaceLog;
import com.qixin.modules.log.service.ISysInterfaceLogService;
import com.qixin.modules.rzInvoice.service.IEaBillService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.TaskListener;
import org.jeecg.common.nc.enums.WSEnum;
import org.jeecg.common.nc.service.NCWebService;
import org.jeecg.common.nc.vo.WSVO;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.activiti.entity.ActBusiness;
import org.jeecg.modules.activiti.entity.ActZTask;
import org.jeecg.modules.activiti.service.IActZTaskService;
import org.jeecg.modules.activiti.service.Impl.ActBusinessServiceImpl;
import org.jeecg.modules.nc.service.INcBdPsnjobService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/***
* @Description: 还款单费用报销推送NC报销审核通过接口
* @author: CYS
* @date: 2022/3/15 11:41
*/
@Slf4j
@Service
public class EaRepaymentbillBXNCItfServiceImpl implements IEaRepaymentbillBXNCItfService {


    @Autowired
    private IEaLoanbillService iEaLoanbillService;
    @Autowired
    private IActZTaskService iActZTaskService;
    @Autowired
    private IEaRepaymentbillService iEaRepaymentbillService;

    @Value(value = "${qixin.ncserver.uri}")
    private  String nCUrl;

    @Override
    public SysInterfaceLog bXApprove(ActBusiness actBusiness, String billNo) throws Exception {
        SysInterfaceLog sysInterfaceLog = new SysInterfaceLog();
        sysInterfaceLog.setBusinessNo(billNo);

            //查询还款单报销头
            EaRepaymentbill eaRepaymentbill = iEaRepaymentbillService.getById(actBusiness.getTableId());
            if(null==eaRepaymentbill){
                throw new RuntimeException("根据"+actBusiness.getTableId()+"TableId查询还款单空！");
            }
            EaListenerUtil.objectDefault(eaRepaymentbill,EaRepaymentbill.class);

            //查询借款单报销头
            QueryWrapper<EaLoanbill> eaLoanbillQueryWrapper=new QueryWrapper<>();
            eaLoanbillQueryWrapper.eq("ea_repaymentbill_id",actBusiness.getTableId());
            List<EaLoanbill> eaLoanbillList = iEaLoanbillService.list(eaLoanbillQueryWrapper);
            if(null==eaLoanbillList||eaLoanbillList.size()==0){
                throw new RuntimeException("根据"+actBusiness.getTableId()+"TableId查询还款单关联借款单报销集合为空！");
            }


            /*
          进入start相关事件调用WSDL在做处理
            */

                JSONObject jsonObject = new JSONObject();
                
                
                try {
                    //表头表体承载对象
                    JSONObject jsonHead = new JSONObject();

                    //根据表id查询任务记录最后审批人
                    ActZTask actZTask = iActZTaskService.getActZTaskByTableId(actBusiness.getProcInstId());

                    String userId = null;
                    int i = 0;
                    while (true){
                        i++;
                        userId = iActZTaskService.getActHiIdentitylinkById(actZTask.getProcInstId(), actZTask.getTaskId());

                        if(StrUtil.isNotEmpty(userId) || i==100){
                            break;
                        }
                        Thread.sleep(3000);
                    }
                    if(StrUtil.isEmpty(userId)){
                        throw new RuntimeException("根据表id查询任务记录最后审批人失败！");
                    }

                    
                    /*
                    表头封装
                     */
                    // 本币金额=实际报销金额
                    jsonHead.put("bbje",0);
                    // 本币余额=实际付款金额
                    jsonHead.put("bbye",0);
                    jsonHead.put("bzbm","1002Z0100000000001K1");
                    // 冲借款本币金额= -还款金额
                    jsonHead.put("cjkbbje",eaRepaymentbill.getRepaymentAmount());
                    // 冲借款原币金额= -还款金额
                    jsonHead.put("cjkybje",eaRepaymentbill.getRepaymentAmount());
                    // 创建人=创建人-用户主键
                    jsonHead.put("creator",eaRepaymentbill.getCreateBy());
                    // 原报销人部门=报销人部门-组织_部门
                    jsonHead.put("deptid",eaRepaymentbill.getDeptId());
                    // 报销人部门=报销人部门-组织_部门版本信息
                    jsonHead.put("deptid_v",eaRepaymentbill.getDeptId());
                    jsonHead.put("djbh",eaRepaymentbill.getBillNo());
                    // 单据大类=bx-bx
                    jsonHead.put("djdl","bx");
                    // 单据类型编码=2647-还款单:2647
                    jsonHead.put("djlxbm","2647");
                    // 单据日期=单据日期-2021-12-15 09:32:43
                    jsonHead.put("djrq", DateUtil.format(eaRepaymentbill.getBillDate(),"yyyy-MM-dd HH:mm:ss") );
                    // 单据状态=3-0=暂存，1=保存，2=审核，3=签字，-1=作废，
                    jsonHead.put("djzt",eaRepaymentbill.getState());
                    // 原费用承担单位=费用承担单位-组织
                    jsonHead.put("fydwbm",eaRepaymentbill.getCostCompCodeId());
                    // 报销人单位=报销人单位
                    jsonHead.put("fydwbm_v",eaRepaymentbill.getCostCompCodeId());
                    // 删除标志=0-0
                    jsonHead.put("dr","0");
                    // 本币汇率=默认为1
                    jsonHead.put("bbhl","1");
                    // 原报销人单位=//原报销人单位
                    jsonHead.put("dwbm",eaRepaymentbill.getCompanyCodeId());
                    jsonHead.put("dwbm_v",eaRepaymentbill.getCompanyCodeId());
                    // 附件张数=附件张数 否
                    jsonHead.put("fjzs","0");
                    // 原费用承担部门=费用承担部门-组织_部门
                    jsonHead.put("fydeptid",eaRepaymentbill.getCostDept());
                    // 费用承担部门=费用承担部门-组织_部门版本信息
                    jsonHead.put("fydeptid_v",eaRepaymentbill.getCostDept());
                    // 供应商=直接取表头收款人
                    jsonHead.put("hbbm",0);
                    // 还款本币金额= -金额为0
                    jsonHead.put("hkbbje",eaRepaymentbill.getRepaymentAmount());
                    // 还款金额= -金额为0
                    jsonHead.put("hkybje",eaRepaymentbill.getRepaymentAmount());
                    // 报销人=报销人
                    jsonHead.put("jkbxr",eaRepaymentbill.getPersonId());
                    // 结算方式=支付方式
                    jsonHead.put("jsfs",eaRepaymentbill.getPayType());
                    // 签字人=最后审批人(财务)
                    jsonHead.put("jsr",actZTask.getOwnerId());
                    // 会计年度=单据日期年度
                    jsonHead.put("kjnd",DateUtil.year(new DateTime()));
                    // 会计期间=单据日期月份
                    jsonHead.put("kjqj",DateUtil.month(new DateTime()));
                    // 录入人=录入人-用户主键
                    jsonHead.put("operator",eaRepaymentbill.getCreateBy());
                    // 支付状态=3-3=支付完成
                    jsonHead.put("payflag","1");
                    // 支付人=最后审批人(财务)
                    jsonHead.put("payman",actZTask.getOwnerId());
                    jsonHead.put("paytarget","0");
                    // pk_billtype=264X-264X
                    jsonHead.put("pk_billtype","264x");
                    // 集团=集团
                    jsonHead.put("pk_group","0001A110000000000CLJ");
                    // 财务组织=费用承担单位
                    jsonHead.put("pk_fiorg",eaRepaymentbill.getCostCompCodeId());
                    jsonHead.put("pk_jkbx","");
                    // 原报销单位=费用承担单位
                    jsonHead.put("pk_org",eaRepaymentbill.getCostCompCodeId());
                    // 报销单位=费用承担单位
                    jsonHead.put("pk_org_v",eaRepaymentbill.getCostCompCodeId());
                    // 录入人=录入人-用pk_payorg户主键
                    jsonHead.put("pk_payorg",eaRepaymentbill.getCostCompCodeId());
                    // 付款单位=费用承担单位
                    jsonHead.put("pk_payorg_v",eaRepaymentbill.getCostCompCodeId());
                    // 交易类型=NC交易类型主键
                    jsonHead.put("pk_tradetypeid","1001A11000000011GUC5");
                    // 收款人=收款人-收款对象为员工，收款人必填
                    jsonHead.put("receiver",eaRepaymentbill.getPersonId());
                    // 审批状态=审批通过-0=审批未通过，1=审批通过，2=审批进行中，3=提交，-1=自由，
                    jsonHead.put("spzt","-1");
                    // 生效标志=1-0=未生效，1=已生效，
                    jsonHead.put("sxbz","0");
                    // 合计金额=实际付款金额
                    jsonHead.put("total",0);
                    // 原币金额=实际付款金额
                    jsonHead.put("ybje",0);
                    // 审批人=最后审批人(财务)-用户主键
                    jsonHead.put("approver",actZTask.getOwnerId());
                    // 支付本币金额 =实际付款金额
                    jsonHead.put("zfbbje",0);
                    // 支付原币金额 =实际付款金额
                    jsonHead.put("zfybje",0);
                    // 事由=事由
                    jsonHead.put("zy",eaRepaymentbill.getExplainStr());
                    // 收支项目=费用项目
                    jsonHead.put("szxmid",eaRepaymentbill.getIndexId());
                    // 最后审批人编码
                    jsonHead.put("actionCode", "APPROVE" + userId);

                    jsonObject.put("parent",jsonHead);
                    /*
                    表头封装结束
                     */
                    
                    
                    /*
                    封装表体借款单和差距
                     */
                    JSONArray jsonArrayJK = new JSONArray();
                    JSONArray jsonArrayContrast = new JSONArray();

                    int rown=0;
                    //遍历费用明细
                    for (EaLoanbill eaLoanbill : eaLoanbillList){
                        JSONObject jsonObjectJK = new JSONObject();
                        // 币种=人民币-币种主键，直接取人民币主键
                        jsonObjectJK.put("bzbm","1002Z0100000000001K1");
                        // 冲借款原币金额= -还款金额
                        jsonObjectJK.put("cjkybje",eaLoanbill.getLoanAmount());
                        // 原报销人部门=报销人部门-组织_部门5674
                        jsonObjectJK.put("deptid",eaLoanbill.getDeptId());
                        // 单据编号=单据编号
                        jsonObjectJK.put("djbh",eaLoanbill.getBillNo());
                        // 单据类型编码=2631-借款单:2631
                        jsonObjectJK.put("djlxbm","2631");
                        jsonObjectJK.put("djrq",DateUtil.format(eaLoanbill.getBillDate(),"yyyy-MM-dd HH:mm:ss") );
                        // 还款金额= -金额为0
                        jsonObjectJK.put("hkybje",eaLoanbill.getLoanAmount());
                        jsonObjectJK.put("jkbxr",eaLoanbill.getPersonId());
                        jsonObjectJK.put("operator",eaLoanbill.getCreateBy());
                        // 报销单标识 =主表主键-n
                        jsonObjectJK.put("pk_jkbx","");
                        jsonObjectJK.put("pk_org",eaLoanbill.getCostCompCodeId());
                        jsonObjectJK.put("pk_payorg",eaLoanbill.getCostCompCodeId());
                        jsonObjectJK.put("spzt",-1);
                        // 原币金额=实际付款金额
                        jsonObjectJK.put("ybje",eaLoanbill.getLoanAmount());
                        // 原币余额=实际付款金额
                        jsonObjectJK.put("ybye",eaLoanbill.getLoanAmount());
                        jsonObjectJK.put("yjye",eaLoanbill.getLoanAmount());
                        jsonArrayJK.add(jsonObjectJK);

                        JSONObject jsonObjectContrast = new JSONObject();
                        jsonObjectContrast.put("bbje",eaLoanbill.getLoanAmount());
                        jsonObjectContrast.put("cjkbbje",eaLoanbill.getLoanAmount());
                        // 冲借款原币金额= -还款金额
                        jsonObjectContrast.put("cjkybje",eaLoanbill.getLoanAmount());
                        // 原报销人部门=报销人部门-组织_部门
                        jsonObjectContrast.put("deptid",eaLoanbill.getDeptId());
                        jsonObjectContrast.put("djlxbm","2631");
                        // 还款本币金额= -金额为0
                        jsonObjectContrast.put("hkybje",eaLoanbill.getLoanAmount());
                        // 报销人=报销人
                        jsonObjectContrast.put("jkbxr",eaLoanbill.getPersonId());
                        jsonObjectContrast.put("jkdjbh",eaLoanbill.getBillNo());
                        // 报销单业务行标识=子表主键
                        jsonObjectContrast.put("pk_busitem","");
                        jsonObjectContrast.put("pk_jkd","");
                        jsonObjectContrast.put("pk_org",eaLoanbill.getCostCompCodeId());
                        // 录入人=录入人-用pk_payorg户主键
                        jsonObjectContrast.put("pk_payorg",eaLoanbill.getCostCompCodeId());
                        // 原币金额=实际付款金额
                        jsonObjectContrast.put("ybje",eaLoanbill.getLoanAmount());
                        // 报销单标识 =主表主键-n
                        jsonObjectContrast.put("pk_jkbx","");
                        // 收款对象=收款对象-0=员工，1=供应商，2=客户，
                        jsonObjectContrast.put("paytarget","0");
                        jsonObjectContrast.put("receiver","");
                        jsonObjectContrast.put("hbbm","");
                        // 行号=行号-n
                        jsonObjectContrast.put("rowno",rown++);
                        // 收支项目=费用项目
                        jsonObjectContrast.put("szxmid",eaLoanbill.getIndexId());
                        jsonArrayContrast.add(jsonObjectContrast);
                    }

                    jsonObject.put("contrast",jsonArrayContrast);
                    jsonObject.put("JKHead",jsonArrayJK);
                    /*
                    封装表体借款单和差距结束
                     */
                    

                    //调用WSDL
                    WSVO wsvo = NCWebService.sendToWS(nCUrl, WSEnum.REPAYMENTBILL, jsonObject.toJSONString());

                    //日志保存
                    if(!wsvo.getStatus()){
                        throw new RuntimeException(wsvo.getMessage());
                    }
                    sysInterfaceLog.setState("1");
                    sysInterfaceLog.setDisposeState("0");
                    sysInterfaceLog.setResult(wsvo.getMessage());
                } catch (Exception e) {
                    sysInterfaceLog.setState("0");
                    sysInterfaceLog.setDisposeState("1");
                    sysInterfaceLog.setResult(e.getMessage());
                }
        sysInterfaceLog.setContent(jsonObject.toJSONString());
        sysInterfaceLog.setCreateTime(new DateTime());
        return sysInterfaceLog;
    }





}
